<template>
  <n-data-table :columns="columns" :data="data" :pagination="paginations" :bordered="false" />
</template>
<script lang="ts" setup>
  import { ref, unref, reactive, onMounted, computed, defineComponent, h } from 'vue';
  import { anchorDark, useMessage, NButton } from 'naive-ui';
  import type { DataTableColumns } from 'naive-ui';
  import { getUserInfo } from '@/api/Demo/Demo';
  import { useRoute } from 'vue-router';
  const message = useMessage();
  const emits = defineEmits(['send']);

  // 标头数据
  const columns = [
    {
      title: 'ID',
      key: 'id',
    },
    {
      title: '姓名',
      key: 'name',
    },
    {
      title: '性别',
      key: 'sex',
    },
    {
      title: '操作',
      key: 'actions',
      render(row) {
        return h('div', [
          h(
            NButton,
            {
              strong: true,
              tertiary: true,
              size: 'small',
              onClick: () => add(row),
              style: { marginRight: '10px' },
            },
            { default: () => '新增' }
          ),
          h(
            NButton,
            {
              strong: true,
              tertiary: true,
              size: 'small',
              onClick: () => edit(row),
            },
            { default: () => '编辑' }
          ),
        ]);
      },
    },
  ];

  // 组件参数
  const props = defineProps({
    pageParam: {
      type: Object,
      required: true,
    },
  });

  // 获取当前路由
  const route = useRoute();
  // 从路由参数中获取 id
  const pageId = route.query.id;
  console.log('id', pageId);

  // 新增
  const add = (row) => {
    // 发送新增消息
    emits('send', 'openAddForm');
  };

  // 编辑
  const edit = (row) => {
    // 发送编辑消息
    emits('send', 'openEditForm', row);
  };

  // 刷新数据回调用方法
  function refresh(params) {
    // 判断params是否传递参数，传递参数需要保存，防止翻页丢失搜索条件
    if (params) {
      Object.assign(searchParams, params);
    }
    search(); // 重新获取列表数据
  }

  // 列表数据
  const data = ref([]);

  const paginations = reactive({
    page: 1,
    pageSize: 10,
  });
  const total = ref(0);

  // 保存搜索参数
  const searchParams = reactive({
    one: null,
    two: null,
  });

  // 列表获取数据
  const search = async () => {
    const params = { ...paginations, ...searchParams };
    const res = await getUserInfo(params);
    data.value = res.data;
    total.value = res.total;
  };

  function init() {
    search();
  }

  // 表格需要暴露出init、refresh方法
  defineExpose({
    init,
    refresh,
  });
</script>
